package com.ztgf.sms.service.sms;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xuanwu.mos.common.entity.GsmsResponse;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.SignUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.file.models.dto.FileUserDTO;
import com.ztgf.file.models.service.IFileUserService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoTypeVO;
import com.ztgf.sms.common.GetALPostMsg;
import com.ztgf.sms.common.GetDCPostMsg;
import com.ztgf.sms.common.GetXWPostMsg;
import com.ztgf.sms.common.config.YmlConfig;
import com.ztgf.sms.constant.SMSConstant;
import com.ztgf.sms.constant.SMSTemplateConstant;
import com.ztgf.sms.mapper.sms.SmsInfoMapper;
import com.ztgf.sms.models.bo.*;
import com.ztgf.sms.models.dto.sms.SmsInfoDTO;
import com.ztgf.sms.models.dto.sms.SmsPassagewayDTO;
import com.ztgf.sms.models.dto.sms.SmsUserDTO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sms.models.service.ISmsPassagewayService;
import com.ztgf.sms.models.service.ISmsUserService;
import com.ztgf.sms.models.vo.DCResultVO;
import com.ztgf.sms.models.vo.SmsInfoVO;
import com.ztgf.sys.models.bo.SysNoticeQueryBO;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.dto.SysNoticeDTO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.service.ISysNoticeService;
import com.ztgf.user.models.service.IUserInfoService;
import com.ztgf.user.models.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * 短信实现类
 *
 * @author zhanghaulang
 * @Date 2020-05-20
 */
@DubboService
@Slf4j
public class SmsInfoServiceImpl extends ServiceImpl<SmsInfoMapper, SmsInfoDTO> implements ISmsInfoService {

    @Value(value = "${sms.account}")
    private String sms_account; //短信账号

    @Value(value = "${sms.password}")
    private String sms_password; //短信密码

    @Value(value = "${sms.timeout}")
    private String sms_timeout; //验证码过期时间（秒）

    @Value(value = "${sys-url}")
    private String sysUrl;

    @Value(value = "${sms.smsUrl}")
    private String sms_smsUrl; //SSO短信接收地址

    @Value(value = "${sms.TENANTID}")
    private String sms_TENANT_ID; //SSO短信TENANT_ID

    @Value(value = "${sms.appid}")
    private String sms_appid; //SSO短信appid

    @Resource
    private YmlConfig ymlConfig;

    @Resource
    private GetXWPostMsg getXWPostMsg;

    @Resource
    private GetDCPostMsg getDCPostMsg;

    @Resource
    private GetALPostMsg getALPostMsg;

    @DubboReference
    private IShopInfoService iShopInfoService;

    @DubboReference
    private IFileUserService iFileUserService;

    @Autowired
    private RedisUtil redisUtil;

    @DubboReference
    private ISysNoticeService iSysNoticeService;

    @DubboReference
    private IUserInfoService userInfoService;
    @DubboReference
    private ISmsUserService iSmsUserService;
    @DubboReference
    private ISmsPassagewayService iSmsPassagewayService;

    /**
     *
     */
    @Override
    @Async
    public void save(SmsInfoSaveBO bo) throws Exception {
        String useType = getSMSUseType();

        switch (useType) {
            case "1":
                xwSend(bo);//发送手机验证码; 对接玄武
                break;
            case "2":
                dcSend(bo);//发送手机验证码; 对接成都创信
                break;
            default:
                xwSend(bo);//发送手机验证码; 对接玄武
                break;
        }
    }

    @Override
    @Async
    public void saveBatch(SmsInfoBatchBO bo, String sessionId, String source) throws Exception {
        SysUserDTO sysUserDTO = (SysUserDTO) redisUtil.getSession(sessionId, source);
        HashMap<String, String> batchMap = getMobile(bo);
        GsmsResponse resp = getXWPostMsg.sendBatchSMS(batchMap);
        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
        if (bo.getType().equals(6)) {
            smsInfoSaveBO.setMobile(batchMap.get("mobile"));
        } else {
            smsInfoSaveBO.setMobile(batchMap.get("mobilename"));
        }
        smsInfoSaveBO.setContent(bo.getContent());
        smsInfoSaveBO.setCreateUserId(sysUserDTO.getId());
        smsInfoSaveBO.setName(batchMap.get("name"));
        smsInfoSaveBO.setType(2);//短信类型 0验证码、1订单通知 2后台推送
        if (resp.getResult() == 0) {
            smsInfoSaveBO.setStatus(0);//发送状态置为成功
        } else {
            smsInfoSaveBO.setStatus(1);//发送状态置为失败
        }
        add(smsInfoSaveBO); //保存消息记录
    }

    @Override
    @Async
    public void saveCaptcha(SmsInfoSaveCaptchaBO smsInfoSaveCaptchaBO) throws Exception {
        String code = getCaptchaCode();//生成验证码
        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
        BeanUtils.copyProperties(smsInfoSaveCaptchaBO, smsInfoSaveBO);
        smsInfoSaveBO.setCode(code);
        String content = String.format(SMSTemplateConstant.CAPTCHA, code);
        switch (smsInfoSaveCaptchaBO.getCaptchaType()) {
            case 0:
                content = String.format(SMSTemplateConstant.REGISTER_CAPTCHA, code);
                break;
            case 1:
                content = String.format(SMSTemplateConstant.LOGIN_CAPTCHA, code);
                break;
            case 2:
                content = String.format(SMSTemplateConstant.PASSWORD_CAPTCHA, code);
                break;
            case 3:
                content = String.format(SMSTemplateConstant.BIND_CAPTCHA, code);
                break;
            case 4:
                content = String.format(SMSTemplateConstant.PAY_CAPTCHA, code);
                break;
            case 6:
                content = String.format(SMSTemplateConstant.PAY_MOBILE_CAPTCHA, code);
                break;
            case 8:
                content = String.format(SMSTemplateConstant.BACKSTAGE_PASSWORD_CAPTCHA, code);
                break;
            case 9:
                content = String.format(SMSTemplateConstant.FREEZE_CAPTCHA, code);
                break;
            case 10:
                content = String.format(SMSTemplateConstant.CLOSE_CAPTCHA, code);
                break;
            case 11:
                content = String.format(SMSTemplateConstant.PAY_REGISTER_CAPTCHA, code);
                break;
            default:
                content = String.format(SMSTemplateConstant.CAPTCHA, code);
                break;
        }
        smsInfoSaveBO.setContent(content);
        smsInfoSaveBO.setIsVerify(0);//初始化未验证

        String useType = getSMSUseType();

        switch (useType) {
            case "1":
                xwSend(smsInfoSaveBO);//发送手机验证码; 对接玄武
                break;
            case "2":
                dcSend(smsInfoSaveBO);//发送手机验证码; 对接成都创信
                break;
            default:
                xwSend(smsInfoSaveBO);//发送手机验证码; 对接玄武
                break;
        }
    }

    @Override
    @Async
    public void sendCaptcha(SmsInfoSaveCaptchaBO smsInfoSaveCaptchaBO) throws Exception {
        UserInfoVO vo = userInfoService.getVo(smsInfoSaveCaptchaBO.getShopId());
        String code = getCaptchaCode();//生成验证码
        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
        BeanUtils.copyProperties(smsInfoSaveCaptchaBO, smsInfoSaveBO);
        smsInfoSaveBO.setCode(code);
        smsInfoSaveBO.setMobile(vo.getMobile());
        String content = String.format(SMSTemplateConstant.CAPTCHA, code);
        switch (smsInfoSaveCaptchaBO.getCaptchaType()) {
            case 0:
                content = String.format(SMSTemplateConstant.REGISTER_CAPTCHA, code);
                break;
            case 1:
                content = String.format(SMSTemplateConstant.LOGIN_CAPTCHA, code);
                break;
            case 2:
                content = String.format(SMSTemplateConstant.PASSWORD_CAPTCHA, code);
                break;
            case 3:
                content = String.format(SMSTemplateConstant.BIND_CAPTCHA, code);
                break;
            case 4:
                content = String.format(SMSTemplateConstant.PAY_CAPTCHA, code);
                break;
            case 6:
                content = String.format(SMSTemplateConstant.PAY_MOBILE_CAPTCHA, code);
                break;
            case 8:
                content = String.format(SMSTemplateConstant.BACKSTAGE_PASSWORD_CAPTCHA, code);
                break;
            case 9:
                content = String.format(SMSTemplateConstant.FREEZE_CAPTCHA, code);
                break;
            case 10:
                content = String.format(SMSTemplateConstant.CLOSE_CAPTCHA, code);
                break;
            case 11:
                content = String.format(SMSTemplateConstant.PAY_REGISTER_CAPTCHA, code);
                break;
            default:
                content = String.format(SMSTemplateConstant.CAPTCHA, code);
                break;
        }
        smsInfoSaveBO.setContent(content);
        smsInfoSaveBO.setIsVerify(0);//初始化未验证

        String useType = getSMSUseType();

        switch (useType) {
            case "1":
                xwSend(smsInfoSaveBO);//发送手机验证码; 对接玄武
                break;
            case "2":
                dcSend(smsInfoSaveBO);//发送手机验证码; 对接成都创信
                break;
            default:
                xwSend(smsInfoSaveBO);//发送手机验证码; 对接玄武
                break;
        }
    }

    @Override
    public boolean add(SmsInfoSaveBO smsInfoSaveBO) {
        SmsInfoDTO smsInfoDTO = new SmsInfoDTO();
        BeanUtils.copyProperties(smsInfoSaveBO, smsInfoDTO);
        Long id = ymlConfig.getPkId();
        smsInfoDTO.setId(id);
        return this.insert(smsInfoDTO);
    }

    @Override
    public boolean getCaptcha(SmsInfoBO smsInfoBO) {
        Wrapper<SmsInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", smsInfoBO.getMobile()); //手机号
        wrapper.eq("status", 0); //状态 发送成功
        wrapper.eq("type", 0); //类型 验证码
        wrapper.eq("is_verify", 0); //未验证
        wrapper.eq("captcha_type", smsInfoBO.getCaptchaType());
//        @ApiModelProperty(value = "验证类型 0注册验证码，1登录验证码，2修改密码验证码，3更改绑定手机验证码，4支付验证码，5保证金修改")

        wrapper.orderBy("create_time", false); //默认倒序

        wrapper.last("LIMIT 1"); //取第一条

        SmsInfoDTO smsInfoDTO = this.selectOne(wrapper);
        if (smsInfoDTO == null) {
            return false;
        }
        return verCaptcha(smsInfoDTO, smsInfoBO.getContent());
    }

    @Override
    public void xwSend(SmsInfoSaveBO bo) throws Exception {
        GsmsResponse resp = getXWPostMsg.sendSMS(bo.getMobile(), bo.getContent());
        if (resp.getResult() == 0) {
            bo.setStatus(0);//发送状态置为成功
        } else {
            bo.setStatus(1);//发送状态置为失败
        }
        add(bo); //保存消息记录
    }

    @Override
    public void saveALCaptcha(SmsInfoSaveCaptchaBO bo) throws Exception {
        String code = getCaptchaCode();//生成验证码
        String modelCode = "";
        //验证类型 0身份验证验证码，1登录确认验证码，2登录异常验证码，3用户注册验证码，4修改密码验证码，5信息变更验证码
        switch (bo.getCaptchaType()) {
            case 0:
                modelCode = SMSConstant.SMS_CARD_CODE;
                break;
            case 1:
                modelCode = SMSConstant.SMS_LOGIN_CODE;
                break;
            case 2:
                modelCode = SMSConstant.SMS_LOGIN_ERROR_CODE;
                break;
            case 3:
                modelCode = SMSConstant.SMS_LOGIN_REGISTERED_CODE;
                break;
            case 4:
                modelCode = SMSConstant.SMS_PASSWORD_UPDATE_CODE;
                break;
            case 5:
                modelCode = SMSConstant.SMS_INFO_CHANGE_CODE;
                break;
            default:
                modelCode = SMSConstant.SMS_LOGIN_CODE;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("code", code);
        boolean flag = getALPostMsg.SendMSM(bo.getMobile(), modelCode, map);

        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
        smsInfoSaveBO.setCode(code);
        smsInfoSaveBO.setContent(code);
        smsInfoSaveBO.setIsVerify(0);//初始化未验证
        smsInfoSaveBO.setType(0);
        smsInfoSaveBO.setMobile(bo.getMobile());
        if (flag) {
            smsInfoSaveBO.setStatus(0);//发送状态置为成功
        } else {
            smsInfoSaveBO.setStatus(1);//发送状态置为失败
        }
        add(smsInfoSaveBO); //保存消息记录
    }

    @Override
    public Page<SmsInfoVO> queryPageList(SmsInfoQueryBO bo) {
        Page<SmsInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<SmsInfoVO> vos = baseMapper.queryPageList(page, bo);
        page.setRecords(vos);
        return page;
    }

    @Override
    @Async
    public void dcSend(SmsInfoSaveBO bo) {
        String reult = getDCPostMsg.sendSMS(bo.getMobile(), bo.getContent());
        if (reult.contains("Success")) {
            bo.setStatus(0);//发送状态置为成功
        } else {
            bo.setStatus(1);//发送状态置为失败
        }
        add(bo); //保存消息记录
    }

    /**
     * 生成短信验证码并存储.
     *
     * @return String
     */
    private String getCaptchaCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 6; i++) {
            // 生成一个[0,10)
            int randomInt = random.nextInt(10);
            str.append(randomInt);
        }
        return str.toString();
    }

    private boolean verCaptcha(SmsInfoDTO smsInfoDTO, String captcha) {
        if (!captcha.equals(smsInfoDTO.getCode())) {
            log.info("==============captcha==="+captcha+smsInfoDTO.getCode());
            return false; //验证码不一致
        }

        Long now_m = System.currentTimeMillis(); //获取当前时间毫秒数
        Long now_s = smsInfoDTO.getCreateTime().getTime(); //获取验证码发送时间毫秒数
        Long time_out = Long.valueOf(sms_timeout) * 1000; //获取验证码过期时间，秒
        Long time = now_s + time_out;
        if (time < now_m) {
            log.info("==============time===now_m==="+time+now_m);
            //超时
            return false;
        }

        smsInfoDTO.setIsVerify(1); //已验证
        return this.updateById(smsInfoDTO);
    }

    private HashMap<String, String> getMobile(SmsInfoBatchBO bo) {
        HashMap<String, String> map = new HashMap<String, String>();
        if (bo.getType().equals(6)) {
            ShopInfoTypeVO vo = iShopInfoService.queryInfoByIds(bo.getShopIds());
            map.put("mobile", vo.getMobile());
            map.put("name", vo.getName());
        } else {
            ShopInfoTypeVO shopInfoTypeVO = iShopInfoService.queryInfoByType(bo.getType());
            map.put("mobile", shopInfoTypeVO.getMobile());
            //发送者类型 0全部用户，1全部店铺，2全部旗舰店，3全部专卖店，4全部专营店，5全部买家，
            switch (bo.getType()) {
                case 0:
                    map.put("name", "全部用户");
                    map.put("mobilename", "全部用户");
                    break;
                case 1:
                    map.put("name", "全部店铺");
                    map.put("mobilename", "全部店铺");
                    break;
                case 2:
                    map.put("name", "全部旗舰店");
                    map.put("mobilename", "全部旗舰店");
                    break;
                case 3:
                    map.put("name", "全部专卖店");
                    map.put("mobilename", "全部专卖店");
                    break;
                case 4:
                    map.put("name", "全部专营店");
                    map.put("mobilename", "全部专营店");
                    break;
                case 5:
                    map.put("name", "全部买家");
                    map.put("mobilename", "全部买家");
                    break;
                default:
                    map.put("name", "其他");
                    map.put("mobilename", "其他");

            }
        }

        map.put("content", bo.getContent());
        return map;
    }

    private String getSMSUseType() {
        RestTemplate restTemplate = new RestTemplate();
        String url = sysUrl + "/sys-client/api/sysDict/getByName";
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();//hashmap无法解析
        map.add("name", SMSConstant.SMS_USE_TYPE);
        String signature = SignUtils.getSignature(map.toSingleValueMap());
        map.add("signature", signature);
        log.info(signature);
        log.info(map.toString());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);//fromdata 方式发送
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        try {
            ResponseEntity<Result> responseEntity = restTemplate.postForEntity(url, request, Result.class);
            if (responseEntity.getBody().getCode() == 0) {
                ObjectMapper objectMapper = new ObjectMapper();
                SysDictDTO dto = objectMapper.convertValue(responseEntity.getBody().getData(), SysDictDTO.class);
                return dto.getValue();
            } else {
                return "";
            }
        } catch (Exception e) {
            return "";
        }
    }

    @Override
    public void savePassAudit(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.PASS_AUDIT);
        save(bo);
    }

    @Override
    public void saveUnPassAudit(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.UN_PASS_AUDIT);
        save(bo);
    }

    @Override
    public void savePassOpenAudit(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.PASS_OPEN_AUDIT);
        save(bo);
    }

    @Override
    public void saveUnPassOpenAudit(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.UN_PASS_OPEN_AUDIT);
        save(bo);
    }

    @Override
    public void saveAfterSale(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.AFTER_SALE);
        save(bo);
    }

    @Override
    public void saveQualificationExpired(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.QUALIFICATION_EXPIRED);
        save(bo);
    }

    @Override
    public void saveQualificationChange(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.QUALIFICATION_CHANGE);
        save(bo);
    }

    @Override
    public void saveOrderStatus(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.ORDER_STATUS);
        save(bo);
    }

    @Override
    public void saveThreshold(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.THRESHOLD);
        save(bo);
    }

    @Override
    public void saveEarnestMoney(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.EARNEST_MONEY);
        save(bo);
    }

    @Override
    public void saveAnnualFee(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.ANNUAL_FEE);
        save(bo);
    }

    @Override
    public void saveFreeze(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.FREEZE);
        save(bo);
    }

    @Override
    public void saveIM(SmsInfoSaveBO bo) throws Exception {
        bo.setContent(SMSTemplateConstant.IM);
        save(bo);
    }

    @Override
    public Result saveOtherDc(SmsInfoOtherSaveBO saveBO) {
        //验证账户是否存在
        FileUserDTO fileUserDTO = iFileUserService.selectById(saveBO.getId());
        if (fileUserDTO == null) {
            return new Result(CodeEnum.FAIL_Login_1001);
        }

        return otherDcSend(saveBO);
    }

    @Override
    public Result getAisleInfo() throws Exception {
        String dc = getDCPostMsg.queryBalance();
        Long xw = getXWPostMsg.doGetAccountInfo().getBalance();

        if (!StringUtils.isEmpty(dc)) {
            DCResultVO vo = JSON.parseObject(dc, DCResultVO.class);
            dc = vo.getOverage();
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("成都创信信息技术有限公司", dc);
        hashMap.put("广州市玄武无线科技股份有限公司", xw);

        return new Result(hashMap);
    }

    @Override
    public Page<SmsInfoDTO> queryAllPageList(SmsInfoQueryBO bo) {
        Wrapper<SmsInfoDTO> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotEmpty(bo.getMobile())) {
            wrapper.like("mobile", bo.getMobile());
        }

        if (bo.getCompanyId() != null) {
            wrapper.eq("company_id", bo.getCompanyId());
        }

        if (bo.getStartDate() != null) {
            wrapper.ge("create_time", bo.getStartDate());
        }

        if (bo.getEndDate() != null) {
            wrapper.le("create_time", bo.getEndDate());
        }

        Page<SmsInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());

        List<SmsInfoDTO> dtoList = baseMapper.selectPage(page, wrapper);
        page.setRecords(dtoList);
        return page;
    }

    @Override
    public void saveBatchByType(SmsInfoBatchBO bo, String sessionId, String source) {
        SysUserDTO sysUserDTO = (SysUserDTO) redisUtil.getSession(sessionId, source);
        String name = "";
        SysNoticeDTO sysNoticeDTO = new SysNoticeDTO ();
        Long id = ymlConfig.getPkId();
        sysNoticeDTO.setId (id);
        sysNoticeDTO.setCreateUserId (sysUserDTO.getId());
        sysNoticeDTO.setStatus (1);  //设置状态为保存成功
        sysNoticeDTO.setType (bo.getStatus ());    //设置状态为短信发送
        sysNoticeDTO.setSendType (bo.getType ());    //设置发送状态:0全部用户，1全部店铺(包含子账户)，2全部旗舰店，3全部专卖店，4全部专营店，5全部买家（全部注册用户），6条件筛选发送
        sysNoticeDTO.setContent (bo.getContent ());
        sysNoticeDTO.setDelFlag (0); //设置状态为未删除

        List<ShopInfoTypeVO> shopInfoTypeVOList = new ArrayList<> ();
        Integer pageNum = 0;
        Integer pageSize = 100;
        do{
            shopInfoTypeVOList=iShopInfoService.queryshopInfoByType(bo.getShopIds(),bo.getType(),pageNum,pageSize);
            if (shopInfoTypeVOList != null && shopInfoTypeVOList.size () >0){
                String shopName = "";
                String mobiles = "";
                for (ShopInfoTypeVO shopInfoTypeVO:shopInfoTypeVOList) {
                    mobiles += shopInfoTypeVO.getMobile ()+ ",";
                    if(bo.getType () == 0 || bo.getType () == 5 ){
                        name += shopInfoTypeVO.getName () + ",";
                        shopName += shopInfoTypeVO.getName () + ",";
                    }else if(bo.getType () == 6){
                        if (bo.getServiceType () == 1){ //条件筛选买家
                            name += shopInfoTypeVO.getName () + ",";
                            shopName += shopInfoTypeVO.getName () + ",";
                        }
                        if (bo.getServiceType () == 2){//条件筛选卖家
                            name += shopInfoTypeVO.getShopName () + ",";
                            shopName += shopInfoTypeVO.getShopName () + ",";
                        }
                    }else {
                        name += shopInfoTypeVO.getShopName () + ",";
                        shopName += shopInfoTypeVO.getShopName () + ",";
                    }
                }
                shopName = shopName.substring (0,shopName.length ()-1);
                mobiles = mobiles.substring (0,mobiles.length ()-1);
                SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
                smsInfoSaveBO.setContent (bo.getContent ()); //存短信内容
                smsInfoSaveBO.setType (2);//短信类型 0验证码、1订单通知 2后台推送
                smsInfoSaveBO.setCreateUserId (sysUserDTO.getId());
                smsInfoSaveBO.setSysNoticeId (sysNoticeDTO.getId ());
                smsInfoSaveBO.setName (shopName);
                smsInfoSaveBO.setMobile (mobiles);
                smsInfoSaveBO.setShopId (Long.parseLong (shopInfoTypeVOList.get (0).getIds ())); //记录每批的第一个id
                smsInfoSaveBO.setStatus(1);//发送状态置为失败
                boolean addFlag = add (smsInfoSaveBO);//保存短信发布日志
                pageNum += pageSize;
                log.info ("保存短信发布日志结果=============" + addFlag);
            }
        }while (shopInfoTypeVOList.size () == pageSize);

        if (bo.getShopIds () != null  && bo.getType ()==6){
            name = name.substring (0,name.length ()-1);
            sysNoticeDTO.setName (name);
            sysNoticeDTO.setShopIds (bo.getShopIds ());
        }
        switch (bo.getType ()){
            case 0:
                sysNoticeDTO.setName ("全部用户");
                break;
            case 1:
                sysNoticeDTO.setName ("全部店铺");
                break;
            case 2:
                sysNoticeDTO.setName ("全部旗舰店");
                break;
            case 3:
                sysNoticeDTO.setName ("全部专卖店");
                break;
            case 4:
                sysNoticeDTO.setName ("全部专营店");
                break;
            case 5:
                sysNoticeDTO.setName ("全部买家");
                break;
        }
        boolean flag = iSysNoticeService.insert (sysNoticeDTO); //保存短信发布记录
        log.info ("保存短信发布记录结果=============" + flag);
    }

    @Override
    public Page<SmsInfoDTO> queryPageListByNoticeId(SysNoticeQueryBO sysNoticeQueryBO) {
        Page<SmsInfoDTO> page = new Page<>(sysNoticeQueryBO.getPageNo(), sysNoticeQueryBO.getPageSize());
        List<SmsInfoDTO> vos = baseMapper.queryPageListByNoticeId(page, sysNoticeQueryBO);
        page.setRecords(vos);
        return page;
    }

    @Override
    public void sendMessageByPurchase(SmsInfoSaveBO smsInfoSaveBO) throws Exception {
        smsInfoSaveBO.setContent(SMSTemplateConstant.PURCHASE_STATUS);
        save(smsInfoSaveBO);
    }

    @Override
    public Result saveOtherPass(SmsInfoOtherSaveBO bo) {
        //验证账户是否存在
        SmsUserDTO smsUserDTO = iSmsUserService.selectById(bo.getId());
        if (smsUserDTO == null) {
            return new Result(CodeEnum.FAIL_Login_1001);
        }
        SmsPassagewayDTO smsPassagewayDTO = iSmsPassagewayService.selectById(smsUserDTO.getPassagewayId());
        if (smsPassagewayDTO == null) {
            return new Result(CodeEnum.FAIL_Login_1001);
        }
        Result<?> result = new Result<>();




//        if (smsUserDTO.getStatus()==1){
//            //阿里
//            HashMap<String, String> map = new HashMap<>();
//            String code = getCaptchaCode();//生成验证码
//            map.put("code", code);
//            try {
//                boolean b = getALPostMsg.SendMSM(bo.getMobile(), bo.getContent(), map);
//                SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
//                smsInfoSaveBO.setCode(code);
//                smsInfoSaveBO.setContent(code);
//                smsInfoSaveBO.setIsVerify(0);//初始化未验证
//                smsInfoSaveBO.setType(0);
//                smsInfoSaveBO.setMobile(bo.getMobile());
//                if (b) {
//                    smsInfoSaveBO.setStatus(0);//发送状态置为成功
//                } else {
//                    smsInfoSaveBO.setStatus(1);//发送状态置为失败
//                }
//                add(smsInfoSaveBO); //保存消息记录
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        }
        if (smsPassagewayDTO.getStauts()==2){
            //创信
            String responseResult= getDCPostMsg.sendSMS(bo.getMobile(), bo.getContent(),bo.getCompanyName());
            log.info("发送短信返回结果:{}", responseResult);
            Map<?, ?> map = JSONObject.parseObject(responseResult);
            // ReturnStatus,响应状态
            String returnStatus = map.get("ReturnStatus").toString();
            // 返回信息
            String returnMessage = map.get("Message").toString();
            log.info("发送短信返回状态:{}", returnStatus);
            if (returnStatus.equals("Success")) {
                bo.setStatus(0);//发送状态置为成功
                addOther(bo); //保存消息记录
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
                return result;
            } else {
                bo.setStatus(1);//发送状态置为失败
                addOther(bo); //保存消息记录
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg(returnMessage);
                return result;
            }
        }
        if (smsPassagewayDTO.getStauts()==3){
            log.info("=========玄武");
            //玄武
            GsmsResponse resp = null;
            try {
                resp = getXWPostMsg.sendSMS(bo.getMobile(), bo.getContent());
                log.info("=========resp"+resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (resp.getResult() == 0) {
                bo.setStatus(0);//发送状态置为成功
                addOther(bo); //保存消息记录
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
                return result;
            } else {
                bo.setStatus(0);//发送状态置为成功
                addOther(bo); //保存消息记录
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
                return result;
            }
        }
        result.setMsg(CodeEnum.FAIL_1000530.getMsg());
        result.setCode(CodeEnum.FAIL_1000530.getCode());
       return result;
    }

    @Override
    public String smsSend(String mobile) {
        log.info("SSO短信参数："+sms_smsUrl+"---"+mobile+"----"+sms_TENANT_ID+"-----"+sms_appid+"-----"+String.format(sms_smsUrl+"%s",mobile));
        return HttpUtil.createGet(String.format(sms_smsUrl+"%s",mobile))
                .header("TENANT-ID", sms_TENANT_ID)
                .header("appId", sms_appid).execute().body();
    }

    public Result otherDcSend(SmsInfoOtherSaveBO bo) {
        Result<?> result = new Result<>();
        String responseResult = getDCPostMsg.sendOtherSMS(bo.getMobile(), bo.getContent());
        log.info("发送短信返回结果:{}", responseResult);
        Map<?, ?> map = JSONObject.parseObject(responseResult);
        // ReturnStatus,响应状态
        String returnStatus = map.get("ReturnStatus").toString();
        // 返回信息
        String returnMessage = map.get("Message").toString();
        log.info("发送短信返回状态:{}", returnStatus);
        if (returnStatus.equals("Success")) {
            bo.setStatus(0);//发送状态置为成功
            addOther(bo); //保存消息记录
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        } else {
            bo.setStatus(1);//发送状态置为失败
            addOther(bo); //保存消息记录
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg(returnMessage);
            return result;
        }
    }

    private void addOther(SmsInfoOtherSaveBO bo) {
        SmsInfoDTO smsInfoDTO = new SmsInfoDTO();
        smsInfoDTO.setMobile(bo.getMobile());
        smsInfoDTO.setStatus(bo.getStatus());
        smsInfoDTO.setContent(bo.getContent());
        smsInfoDTO.setCompanyId(bo.getId());
        Long id = ymlConfig.getPkId();
        smsInfoDTO.setId(id);
        this.insert(smsInfoDTO);
    }
}
